﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using QLKS.Templates;
using System.IO;
using System.Data;
using System.Text.RegularExpressions;

namespace QLKS.Views
{
    /// <summary>
    /// Interaction logic for frmThemNhanVien.xaml
    /// </summary>
    public partial class frmThemNhanVien : FormTrans
    {
        public bool UpdateSucces = false;
        Command cm;
        DataTable Data = new DataTable();

        public frmThemNhanVien()
        {
            InitializeComponent();
        }

        public frmThemNhanVien(DataTable tb, Command _cm)
        {
            InitializeComponent();
            IsEditMode = _cm == Command.View ? false : true;
            cm = _cm;
            cbbChucVu.ItemsSource = ViewModels.NhanVienViewModel.GetNhomNhanVien().DefaultView;

            if (tb == null)
                Data = ViewModels.NhanVienViewModel.CreateNewNhanVien();
            else
                Data = tb.Copy();
            if (cm == Command.Copy)
                Data.Rows[0]["manv"] = ViewModels.NhanVienViewModel.GetMaNhanVien();
            gridMain.DataContext = Data.DefaultView;          
        }

        //Load Image
        private void LoadImage()
        {
            byte[] b = (byte[])Data.Rows[0]["hinhanh"];
            if (b.Length == 0)
                return;
            //picture.ImgSource = null;
            //save file pic
            try
            {
                string ImagePath = "Images\\NV\\" + Data.Rows[0]["manv"].ToString() + ".jpg";
                if (!System.IO.File.Exists(ImagePath))
                {
                    FileStream fs = File.OpenWrite(ImagePath);

                    fs.Write(b, 0, b.Length);
                    // Fill column and close filestream
                    fs.Close();
                }
                picture.ImgSource = System.Windows.Forms.Application.StartupPath + "\\" + ImagePath;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            
        }

        static public Visibility ChangePassword = Visibility.Collapsed;

        public bool IsEditMode
        {
            get { return (bool)GetValue(IsEditModeProperty); }
            set { SetValue(IsEditModeProperty, value); }
        }

        // Using a DependencyProperty as the backing store for IsEditMode.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty IsEditModeProperty =
            DependencyProperty.Register("IsEditMode", typeof(bool), typeof(frmThemNhanVien), new UIPropertyMetadata(true));

        //Kiểm tra dữ liệu hợp lệ
        private bool KiemTra()
        {
            if (string.IsNullOrEmpty(txtMaNV.Text))
            {
                MessageBox.Show(M_LAN.Equals("V")?"Chưa nhập mã":"please input id", "QLKS", MessageBoxButton.OK, MessageBoxImage.Error);
                txtMaNV.Focus();
                return false;
            }
            else
                if (string.IsNullOrEmpty(txtTenNV.Text))
                {
                    MessageBox.Show(M_LAN.Equals("V")?"Chưa nhập họ tên":"input username, please!", "QLKS", MessageBoxButton.OK, MessageBoxImage.Error);
                    txtTenNV.Focus();
                    return false;
                }
                else
                    if (string.IsNullOrEmpty(txtCMND.Text))
                    {
                        MessageBox.Show(M_LAN.Equals("V")?"Chưa nhập CMND":"please input id card number", "QLKS", MessageBoxButton.OK, MessageBoxImage.Error);
                        txtCMND.Focus();
                        return false;
                    }
                    else
                        if (string.IsNullOrEmpty(cbbChucVu.Text))
                        {
                            MessageBox.Show(M_LAN.Equals("V")?"Chưa nhập chức vụ":"please input position", "QLKS", MessageBoxButton.OK, MessageBoxImage.Error);
                            cbbChucVu.Focus();
                            return false;
                        }
                        else
                            if (!string.IsNullOrEmpty(txtEmail.Text))
                                if(CheckEmail(txtEmail.Text))
                                {
                                    MessageBox.Show(M_LAN.Equals("V")?"Email không hợp lệ":"Invalid email", "QLKS", MessageBoxButton.OK, MessageBoxImage.Error);
                                    txtEmail.Focus();
                                    return false;
                                }

            return true;
        }

        //Kiểm tra Email
        private bool CheckEmail(string text)
        {
            string strIn = text;
            if (!Regex.IsMatch(strIn,
             @"^(?("")("".+?""@)|(([0-9a-zA-Z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-zA-Z])@))" +
             @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,6}))$"))
            {
                return false;
            }
            return true;
        }

        private void FrmThemNhanVien_Loaded(object sender, RoutedEventArgs e)
        {
            //tbMain.IsEditMode = IsEditMode;

            if (IsEditMode)
            {
                tbMain.Cm_Save += new ucXToolBar.Execute(tbMain_Cm_Save);
                tbMain.Cm_New += new ucXToolBar.Execute(tbMain_Cm_New);
            }
            if (cm == Command.Edit || cm == Command.View)
                LoadImage();
            string manv = Models.NguoiDungModel.GetMaNhanVien(frmMain._UserName);
            ChangePassword = Data.Rows[0]["manv"].ToString().Equals(manv) ? Visibility.Visible : Visibility.Collapsed;
            txtTenNV.Focus();
            tbMain.Cm_Exit += new ucXToolBar.Execute(tbMain_Cm_Exit);
            MainPage.SetTitle(cm, M_LAN.Equals("V") ? "NHÂN VIÊN" : "STAFF");
        }

        private void tbMain_Cm_Save()
        {
            //Thêm vào CSDL dữ liệu
            if (KiemTra())
            {
                if (ViewModels.NhanVienViewModel.ThemNhanVien(Data, picture.ImageSource))
                {
                    this.UpdateSucces = true;
                    if (cm == Command.Edit)
                        MessageBox.Show(M_LAN.Equals("V")?"Cập nhật nhân viên thành công!":"Update staff successful", "HotelManager", MessageBoxButton.OK, MessageBoxImage.Information);
                    else
                    {
                        MessageBox.Show(M_LAN.Equals("V")?"Thêm nhân viên thành công!":"Insert staff successful", "HotelManager", MessageBoxButton.OK, MessageBoxImage.Information);
                        cm = Command.Edit;
                    }
                }
            }
        }

        private void tbMain_Cm_New()
        {
            Data = ViewModels.NhanVienViewModel.CreateNewNhanVien();
            gridMain.DataContext = Data.DefaultView;
            txtTenNV.Focus();
            cm = Command.New;
        }

        //Đóng form
        public void tbMain_Cm_Exit()
        {
            //picture.ImgSource = null;
            this.Close();
        }

        private void xdgdtNgaySinh_GotFocus(object sender, RoutedEventArgs e)
        {
            xdgdtNgaySinh.SelectAll();
        }

        private void cbbChucVu_GotFocus(object sender, RoutedEventArgs e)
        {
            ComboBox cb = sender as ComboBox;
            if (cb != null)
                cb.IsDropDownOpen = true;
        }

        private void txtChangePassword_Click(object sender, RoutedEventArgs e)
        {
            DataTable tb = ViewModels.LoginViewModel.GetUserInfo(frmMain._UserName);
            if (tb.Rows.Count <= 0)
            {
                MessageBox.Show("Kết nối đã bị ngắt vui lòng đăng nhập lại!", "QLKS", MessageBoxButton.OK, MessageBoxImage.Stop);
                return;
            }
            frmThayDoiMatKhau frm = new frmThayDoiMatKhau(tb);
            frm.ShowDialog();
        }
    }
}
